package com.SpringBoot.location.service;

import com.SpringBoot.Util.Result;
import com.SpringBoot.location.mapper.LocationMapper;
import com.SpringBoot.location.pojo.Location;
import com.SpringBoot.user.mapper.UserMapper;
import com.SpringBoot.user.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * <p>
 * 用户地址表 服务实现类
 * </p>
 *
 * @author bxk
 * @since 2025-09-19
 */
@Service
public class LocationService{

    private final UserMapper userMapper;
    private final UserService userService;
    private final LocationMapper locationMapper;

    public LocationService(UserMapper userMapper, UserService userService, LocationMapper locationMapper) {
        this.userMapper = userMapper;
        this.userService = userService;
        this.locationMapper = locationMapper;
    }

    public Result addLocation(Location location){
        Result userCheck = userService.existUser(location.getUserId());
        if(userCheck.getCode() != 0){
            return userCheck;
        }
        locationMapper.addLocation(location);
        return Result.success("添加地址成功");

    }

    public Result updateLocation(Location location){
        Result userCheck = userService.existUser(location.getUserId());
        if(userCheck.getCode() != 0){
            return userCheck;
        }
        Location existLocation = locationMapper.getLocationById(location.getLocationId());
        if (existLocation == null) {
            return Result.error(404,"改地址不存在");
        }
        locationMapper.updateLocation(location);
        return Result.success("修改成功");
    }

    public Result getLocationByUserId(Integer userId){
        Result userCheck = userService.existUser(userId);
        if(userCheck.getCode() != 0){
            return userCheck;
        }
        ArrayList<Location> locations = locationMapper.getLocationByUserId(userId);
        if(locations == null){
            return Result.error(404,"还没有收获地址，快去添加一个吧");
        }
        return Result.success(locations);
    }

    public Result deleteLocation(Integer locationId){
        locationMapper.deleteLocation(locationId);
        return Result.success("删除成功");
    }

}
